<template>
  <div class="wrapper">
    <header class="mdc-top-app-bar">
      <div class="mdc-top-app-bar__row">
        <section class="mdc-top-app-bar__section mdc-top-app-bar__section--align-start">
          <BackButton />
          <h1 class="mdc-top-app-bar__title">我的收藏</h1>
        </section>
      </div>
    </header>

    <div class="favorites-container" v-if="user && user.userId">
      <div v-if="loading" class="empty-text">加载中...</div>
      <div v-else-if="favorites.length === 0" class="empty-text">还没有收藏任何商家</div>
      <div v-else>
        <div
          v-for="item in favorites"
          :key="item.businessId"
          class="business-card"
        >
          <div class="business-img-wrapper" @click="toBusinessInfo(item.businessId)">
            <img :src="getImg(item.businessImg)" @error="handleImageError" class="business-img" />
          </div>
          <div class="business-info" @click="toBusinessInfo(item.businessId)">
            <h3 class="business-name">{{ item.businessName }}</h3>
            <div class="business-meta">
              <span class="meta-item">¥{{ item.starPrice }}起送</span>
              <span class="meta-divider">|</span>
              <span class="meta-item">¥{{ item.deliveryPrice }}配送</span>
            </div>
            <p class="business-desc">{{ item.businessExplain }}</p>
          </div>
          <button class="favorite-btn active" @click.stop="removeFavorite(item.businessId)">
            <i class="material-icons">favorite</i>
            <span>取消收藏</span>
          </button>
        </div>
      </div>
    </div>

    <div v-else class="empty-text">
      请先登录后查看收藏
    </div>

    <AppFooter></AppFooter>
  </div>
</template>

<script>
import AppFooter from '../components/AppFooter.vue';
import BackButton from '../components/BackButton.vue';

export default {
  name: 'MyFavorites',
  components: { AppFooter, BackButton },
  data() {
    return {
      user: {},
      favorites: [],
      loading: false,
    };
  },
  created() {
    this.user = this.$getSessionStorage('user');
    if (!this.user || !this.user.userId) {
      this.$toast?.info('请先登录');
      this.$router.push('/login');
      return;
    }
    this.loadFavorites();
  },
  methods: {
    getImg(path) {
      if (!path) return this.getDefaultImage();
      if (path.startsWith('http')) return path;
      if (path.startsWith('data:image')) return path;
      if (path.startsWith('/')) {
        if (path.startsWith('/img/')) {
          return 'http://localhost:8888' + path;
        }
        return 'http://localhost:8888/img' + path;
      }
      return 'http://localhost:8888/img/' + path;
    },
    getDefaultImage() {
      const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200"><rect width="200" height="200" fill="#f5f5f5" rx="10"/><text x="100" y="100" font-size="80" text-anchor="middle" dominant-baseline="central">❤</text></svg>';
      return 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
    },
    handleImageError(event) {
      event.target.src = this.getDefaultImage();
    },
    loadFavorites() {
      if (!this.user || !this.user.userId) return;
      this.loading = true;
      this.$axios
        .get('favorites/list', {
          params: { userId: this.user.userId },
        })
        .then((resp) => {
          if (resp.data && (resp.data.code === 200 || resp.data.code === '200')) {
            this.favorites = resp.data.result || [];
          } else {
            this.favorites = [];
          }
        })
        .catch((err) => {
          console.error('获取收藏列表失败:', err);
          this.$toast?.error('获取收藏列表失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    removeFavorite(businessId) {
      if (!this.user || !this.user.userId) {
        this.$toast?.info('请先登录');
        this.$router.push('/login');
        return;
      }
      this.$axios
        .post('favorites/remove', null, {
          params: {
            userId: this.user.userId,
            businessId,
          },
        })
        .then((resp) => {
          if (resp.data && (resp.data.code === 200 || resp.data.code === '200')) {
            this.$toast?.success('已取消收藏');
            this.favorites = this.favorites.filter((b) => b.businessId !== businessId);
          } else {
            this.$toast?.error(resp.data.message || '取消收藏失败');
          }
        })
        .catch((err) => {
          console.error('取消收藏失败:', err);
          this.$toast?.error('取消收藏失败');
        });
    },
    toBusinessInfo(businessId) {
      this.$router.push({ path: '/businessInfo', query: { businessId } });
    },
  },
};
</script>

<style scoped>
.wrapper {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 14vw;
}

.mdc-top-app-bar {
  background-color: #1976d2;
  color: white;
  position: sticky;
  top: 0;
  z-index: 100;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.mdc-top-app-bar__row {
  display: flex;
  align-items: center;
  height: 72px;
  padding: 0 20px;
}

.mdc-top-app-bar__section {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-direction: row;
}

.mdc-top-app-bar__title {
  font-size: 22px;
  font-weight: 500;
  margin: 0;
  white-space: nowrap;
  line-height: 1;
}

.favorites-container {
  padding: 0 3vw;
}

.business-card {
  width: 100%;
  background-color: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 3vw;
  padding: 4vw;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
  user-select: none;
}

.business-img-wrapper {
  position: relative;
  flex-shrink: 0;
}

.business-img {
  width: 22vw;
  height: 22vw;
  border-radius: 12px;
  object-fit: cover;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.business-info {
  flex: 1;
  margin-left: 4vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.business-name {
  font-size: 4.2vw;
  font-weight: 600;
  color: #333;
  margin: 0 0 2vw 0;
}

.business-meta {
  display: flex;
  align-items: center;
  margin-bottom: 2vw;
  gap: 2vw;
}

.meta-item {
  font-size: 3.2vw;
  color: #666;
}

.meta-divider {
  color: #ddd;
  font-size: 3vw;
}

.business-desc {
  font-size: 3.2vw;
  color: #999;
  margin: 0;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.favorite-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-left: 2vw;
  border: none;
  background: none;
  cursor: pointer;
  color: #999;
}

.favorite-btn .material-icons {
  font-size: 6vw;
}

.favorite-btn span {
  font-size: 2.8vw;
}

.favorite-btn.active {
  color: #ff4d4f;
}

.empty-text {
  padding: 6vw 3vw;
  text-align: center;
  color: #999;
  font-size: 3.4vw;
}
</style>
